package web.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class MpServlet extends HttpServlet {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(MpServlet.class);
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		valid(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
	
	
	public void valid(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		String echostr = request.getParameter("echostr");
		if (null==echostr||echostr.isEmpty()) {
			responseMsg(request,response);
		} else {
			if (this.checkSignature()) {
				 print(echostr,response);
			} else {
				print("error",response);
			}
		}
	}

	//自动回复内容
	public void responseMsg(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		String postStr = null;
		try {
			postStr = this.readStreamParameter(request.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("post is null");
		if (null != postStr && !postStr.isEmpty()) {
			Document document = null;
			try {
				document = DocumentHelper.parseText(postStr);
				logger.info("post is ["+postStr+"]");
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (null == document) {
				this.print("",response);
				return;
			}
			
			/*
			<xml> 
			<URL><![CDATA[http://2.cultgeek.sinaapp.com/wp.jsp]]></URL> 
			<ToUserName><![CDATA[shadowedge]]></ToUserName> 
			<FromUserName><![CDATA[haha]]></FromUserName> 
			<CreateTime>1</CreateTime> 
			<MsgType><![CDATA[text]]></MsgType> 
			<Content><![CDATA[hehe]]></Content>
			<MsgId>1</MsgId> 
			</xml>
			 */
			Element root = document.getRootElement();
		    String fromUsername = root.elementText("FromUserName");
			String toUsername = root.elementText("ToUserName");
			String keyword = root.elementTextTrim("Content");
			String time = new Date().getTime() + "";
			String textTpl = "<xml>"
					+ "<ToUserName><![CDATA[%1$s]]></ToUserName>"
					+ "<FromUserName><![CDATA[%2$s]]></FromUserName>"
					+ "<CreateTime>%3$s</CreateTime>"
					+ "<MsgType><![CDATA[%4$s]]></MsgType>"
					+ "<Content><![CDATA[%5$s]]></Content>"
					+ "<FuncFlag>0</FuncFlag>" + "</xml>";
           
			if (null != keyword && !keyword.equals("")) {
				String msgType = "text";
				String contentStr = "Duang~~~ your message is ["+keyword+"]";
				String base64cont =  Base64.getEncoder().encodeToString(keyword.getBytes());
				String resultStr = textTpl.format(textTpl, fromUsername,
				toUsername, time, msgType, contentStr+",base64 is:\n"+base64cont);
				print(resultStr,response);
			} else {
				this.print("Input something...",response);
			}

		} else {
			this.print("request is null",response);
		}
	}

	//微信接口验证
	public boolean checkSignature() {
		return true;
	/* 	String signature = final_request.getParameter("signature");
		String timestamp = final_request.getParameter("timestamp");
		String nonce = final_request.getParameter("nonce");
		String token = TOKEN;
		String[] tmpArr = { token, timestamp, nonce };
		Arrays.sort(tmpArr);
		String tmpStr = this.ArrayToString(tmpArr);
		tmpStr = this.SHA1Encode(tmpStr);
		if (tmpStr.equalsIgnoreCase(signature)) {
			return true;
		} else {
			return false;
		} */
	}

	//向请求端发送返回数据
	public void print(String content, HttpServletResponse response) {
		try {
			response.getWriter().print(content);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			logger.error("",e);
		}
	}

	//数组转字符串
	private String ArrayToString(String[] arr) {
		StringBuffer bf = new StringBuffer();
		for (int i = 0; i < arr.length; i++) {
			bf.append(arr[i]);
		}
		return bf.toString();
	}

	//sha1加密
	private String SHA1Encode(String sourceString) {
		String resultString = null;
		try {
			resultString = new String(sourceString);
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			resultString = byte2hexString(md.digest(resultString.getBytes()));
		} catch (Exception ex) {
		}
		return resultString;
	}

	private final String byte2hexString(byte[] bytes) {
		StringBuffer buf = new StringBuffer(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			if (((int) bytes[i] & 0xff) < 0x10) {
				buf.append("0");
			}
			buf.append(Long.toString((int) bytes[i] & 0xff, 16));
		}
		return buf.toString().toUpperCase();
	}

	//从输入流读取post参数
	public String readStreamParameter(ServletInputStream in) {
		StringBuilder buffer = new StringBuilder();
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(in));
			String line = null;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != reader) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return buffer.toString();
	}
}